package com.education.teach.mvp.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dn.res.wideget.DnToolbar;
import com.education.teach.R;
import com.education.teach.di.component.DaggerCounselDetailComponent;
import com.education.teach.di.module.CounselDetailModule;
import com.education.teach.mvp.contract.CounselDetailContract;
import com.education.teach.mvp.model.bean.CounselBean;
import com.education.teach.mvp.model.bean.CounselDetailBean;
import com.education.teach.mvp.model.bean.LoginBean;
import com.education.teach.mvp.model.service.ApiService;
import com.education.teach.mvp.presenter.CounselDetailPresenter;
import com.education.teach.mvp.ui.adapter.CounselAdapter;
import com.education.teach.utils.DnCommonUtils;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.utils.ArmsUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import dn.easy.common.commonwidget.AVLoadingDialog;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import static com.jess.arms.utils.Preconditions.checkNotNull;


public class CounselDetailActivity extends BaseActivity<CounselDetailPresenter> implements CounselDetailContract.View, SwipeRefreshLayout.OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R.id.toolbar)
    DnToolbar mToolbar;
    @BindView(R.id.tv_qa_title)
    TextView mTvQaTitle;
    @BindView(R.id.tv_qa_user)
    TextView mTvQaUser;
    @BindView(R.id.tv_qa_date)
    TextView mTvQaDate;
    @BindView(R.id.et_text)
    EditText mEtText;
    @BindView(R.id.btn_qa)
    Button mBtnQa;
    @BindView(R.id.lv_content)
    RecyclerView mRecyclerView;
    @BindView(R.id.swf_pager_list)
    SwipeRefreshLayout mSwipeRereshLayout;
    int maxRow = 999;
    int page = 1;
    private String id;
    private LoginBean mLoginBean;
    private List<CounselBean.ResultBean.QueryListBean> mList = new ArrayList<>();
    private CounselAdapter mAdapter;

    @Inject
    IRepositoryManager mIRepositoryManager;
    @Inject
    RxErrorHandler mRxErrorHandler;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerCounselDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .counselDetailModule(new CounselDetailModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_counsel_detail; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mToolbar.setMainTitle("答疑详情");
        mToolbar.setToolbarLeftBackImageRes(R.mipmap.top_back);
        mToolbar.setOnLeftTitleClickListener(view -> finish());
        mSwipeRereshLayout.setRefreshing(false);
        mSwipeRereshLayout.setEnabled(false);

        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        String createName = intent.getStringExtra("createName");
        String date = intent.getStringExtra("date");
        id = intent.getStringExtra("id");
        String name = intent.getStringExtra("name");
        mTvQaTitle.setText("问题:" + title);
        mTvQaUser.setText("作者：" + createName);
        mTvQaDate.setText(date);
        mLoginBean = DnCommonUtils.getUserModel(this);
        mBtnQa.setOnClickListener(v -> {
            mPresenter.saveConsultationQuestion(mLoginBean.getResult().getXlh(), mEtText.getText().toString(), id, name);
        });
        getData();

    }

    @Override
    public void showLoading() {
        AVLoadingDialog.showDialogForLoading(this);
    }

    @Override
    public void hideLoading() {
        AVLoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void retrunSaveResult(CounselDetailBean counselBean) {
        if (counselBean.getCode() == 0) {
            showMessage("操作成功");
            finish();
        } else
            showMessage("操作失败");
    }

    private CounselBean getData() {

        Map<String, String> map = new HashMap<>();
        LoginBean bean = DnCommonUtils.getUserModel(CounselDetailActivity.this);
        map.put("consultationId", id);
        map.put("currentPage", page + "");
        map.put("maxRows", maxRow + "");
        mIRepositoryManager
                .obtainRetrofitService(ApiService.class)
                .showConsultationQuestion(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<CounselBean>(mRxErrorHandler) {
                    @Override
                    public void onNext(CounselBean counselBean) {
                        if (counselBean.getCode() != 1){
                            mList.addAll(counselBean.getResult().getQueryList());
                        }else{
                            Toast.makeText(CounselDetailActivity.this, "服务器异常，请稍后再试", Toast.LENGTH_SHORT).show();
                        }

                        mLoginBean = DnCommonUtils.getUserModel(CounselDetailActivity.this);
                        mRecyclerView.setLayoutManager(new LinearLayoutManager(CounselDetailActivity.this));
                        mAdapter = new CounselAdapter(R.layout.item_counsel, mList);
                        mRecyclerView.setAdapter(mAdapter);
                    }
                });
        return  null;
    }

    @Override
    public void onRefresh() {
        page = 1;
//        mPresenter.consulQuestionList(mLoginBean.getResult().getXlh(), page, maxRow, true);
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
//        mPresenter.consulQuestionList(mLoginBean.getResult().getXlh(), page, maxRow, false);
    }
}
